package at.fhj.swd10.eshop.web.application;

import at.fhj.swd10.eshop.database.CategoryDao;
import at.fhj.swd10.eshop.database.LabelDao;
import at.fhj.swd10.eshop.database.ProductDao;
import at.fhj.swd10.eshop.domain.Category;
import at.fhj.swd10.eshop.domain.Label;
import at.fhj.swd10.eshop.domain.Product;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

/**
 * @author David
 */
@ManagedBean(name = "shopData")
@ApplicationScoped
public class ShopData implements Serializable {

    private CategoryDao categoryDao = CategoryDao.getCategoryDao();
    private LabelDao labelDao = LabelDao.getLabelDao();
    private ProductDao productDao = ProductDao.getProductDao();
    private List<Category> categoryList;
    private List<Label> labelList;
    private List<Product> productList;

    public ShopData() throws Exception {
        initCategoryList();
        initLabelList();
        initProductList();
    }

    private void initCategoryList() throws Exception {
        categoryList = categoryDao.getCategoryList();
    }

    private void initLabelList() throws Exception {
        labelList = labelDao.getLabelList();
    }

    private void initProductList() throws Exception {
        productList = productDao.getProductList();
    }

    public void insertProduct(Product p) throws Exception {
        productDao.insertProduct(p);
        initProductList();
    }

    public void updateProduct(Product p) throws Exception {
        productDao.updateProduct(p);
        initProductList();
    }

    public void deleteProduct(Product p) throws Exception {
        productDao.deleteProduct(p);
        initProductList();
    }

    public List<Category> getCategoryList() {
        return categoryList;
    }

    public List<Label> getLabelList() {
        return labelList;
    }

    public List<Product> getProductList() {
        Collections.sort(productList);
        return productList;
    }

    public List<Category> getFilterCategoryList() {
        List<Category> categoryFilterList = new ArrayList<Category>();
        categoryFilterList.addAll(categoryList);
        categoryFilterList.add(0, new Category("", ""));
        return categoryFilterList;
    }

    public List<Label> getFilterLabelList() {
        List<Label> labelFilterList = new ArrayList<Label>();
        labelFilterList.addAll(labelList);
        labelFilterList.add(0, new Label("", ""));
        return labelFilterList;
    }

    public Product getProductById(int id) {
        for (Product p : productList) {
            if (p.getId() == id) {
                return p;
            }
        }
        return null;
    }
}
